<template>
    <div class="user-center-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="user-form">
            <!-- 姓名 -->
            <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入姓名" clearable class="custom-input">
                    <i slot="prefix" class="el-icon-user"></i>
                </el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" placeholder="留空表示不修改" show-password clearable
                    class="custom-input">
                    <i slot="prefix" class="el-icon-lock"></i>
                </el-input>
            </el-form-item>

            <!-- 头像 -->
            <el-form-item label="头像" prop="headPicture">
                <div class="avatar-uploader">
                    <div class="upload-wrapper" :class="{ 'has-image': form.headPicture }" @click="triggerFileInput">
                        <div v-if="form.headPicture" class="preview-wrapper">
                            <img :src="form.headPicture" class="preview-image">
                            <div class="mask">
                                <i class="el-icon-upload"></i>
                            </div>
                        </div>
                        <i v-else class="el-icon-plus upload-icon"></i>
                        <input ref="fileInput" type="file" class="hidden-input" accept="image/*"
                            @change="handleFileChange">
                    </div>
                    <div class="upload-tip">支持JPG/PNG格式，大小不超过2MB</div>
                </div>
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item label="手机号" prop="mobilePhone">
                <el-input v-model="form.mobilePhone" placeholder="请输入手机号" clearable class="custom-input">
                    <i slot="prefix" class="el-icon-mobile-phone"></i>
                </el-input>
            </el-form-item>

            <!-- 状态 -->
            <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" class="status-select">
                    <el-option label="启用" :value="1"></el-option>
                    <el-option label="禁用" :value="0"></el-option>
                </el-select>
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm" :loading="loading" class="submit-btn">
                    <i class="el-icon-upload"></i>
                    提交修改
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

import { upload } from '@/api/common/common';
import { UpUser, getUserById } from '@/api/admin/User';
export default {
    props: {
        initialValues: {
            type: Object,
            default: () => ({})
        }
    },

    data() {
        return {
            loading: false,
            fileList: [],
            form: {
                name: '',
                password: '',
                mobilePhone: '',
                status: 0,
                headPicture: '' // 确保表单包含头像字段
            },
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                mobilePhone: [
                    // { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ], headPicture: [
                    { required: true, message: '请上传头像', trigger: 'blur' }
                ],
            }
        }
    },

    watch: {
        initialValues: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    // 深拷贝合并表单数据
                    this.form = {
                        ...this.form,
                        ...JSON.parse(JSON.stringify(newVal))
                    }

                    // 处理头像显示
                    if (newVal.headPicture) {
                        this.fileList = [{
                            uid: '-1',
                            name: 'avatar',
                            status: 'done',
                            url: newVal.headPicture
                        }]
                    } else {
                        this.fileList = []
                    }
                }
            }
        }
    },

    methods: {
        async getUser(userId) {
            console.log('----------------------------------------------');

            try {
                const { data } = await getUserById(userId);
                if (data) {
                    this.form = {
                        id: data.data.id,
                        mobilePhone: data.data.mobilePhone,
                        name: data.data.name?.trim() || '',
                        status: data.data.status,
                        // createTime: data.createTime
                        //     ? dayjs(data.createTime).format('YYYY-MM-DD')
                        //     : dayjs().format('YYYY-MM-DD'),
                        headPicture: data.data.headPicture || ''
                    }
                }
            } catch (error) {
                console.error('商品加载失败:', error)
                this.$message.error('商品信息加载失败')
                this.$router.back()
            }
        },
        triggerFileInput() {
            this.$refs.fileInput.click()
        },
        async handleFileChange(event) {

            const file = event.target.files[0]
            if (!file) return

            try {
                // 这里可以添加文件验证逻辑
                if (!this.beforeUpload(file)) {
                    this.$message.error('请选择有效的图片文件')
                    return
                }
                const res = await upload(file)
                console.log('res', res);

                this.form.headPicture = res
            } catch (error) {
                console.error('上传失败:', error)
                this.$message.error('上传失败，请重试')
            } finally {
                // 重置输入框以允许重复选择同一文件
                event.target.value = null
            }
        },
        beforeUpload(file) {
            const isImage = ['image/jpeg', 'image/png'].includes(file.type)
            const isLt2M = file.size / 1024 / 1024 < 2
            return isImage && isLt2M
        },
        handleUploadChange(file, fileList) {
            // 生成预览URL并更新文件列表

            this.fileList = fileList.slice(-1).map(item => ({
                ...item,
                url: item.url || URL.createObjectURL(item.raw)
            }))

            // 更新表单头像字段（如果需要）
            if (this.fileList.length > 0) {
                this.form.headPicture = this.fileList[0].url
            } else {
                this.form.headPicture = ''
            }
        },

        // 表单提交
        async submitForm() {
            try {
                // const valid = await this.$refs.formRef.validate()
                // if (!valid) return
                const payload = {
                    id: this.form.id,
                    name: this.form.name,
                    password: this.form.password,
                    status: this.form.status,
                    headPicture: this.form.headPicture,
                    mobilePhone: this.form.mobilePhone,
                    // createTime: dayjs(this.form.createTime).valueOf()
                }
                const { data } = await UpUser(payload)
                console.log('data', data);

                if (data.code === 1) {
                    this.$message.success('更新成功')
                    setTimeout(() => {
                        this.$router.push('/home/User')
                    }, 1500)
                } else {
                    this.$message.error(data.msg || '更新失败')
                }
            } catch (error) {
                console.error('更新失败:', error)
                this.$message.error('商品更新失败: ' + (error.response?.data?.msg || '服务器错误'))
            }
        },

        async handleSubmit() {
            try {
                this.loading = true
                const formData = new FormData()

                // 处理文件上传
                if (this.fileList[0]?.raw) {
                    formData.append('avatar', this.fileList[0].raw)
                }

                // 添加其他字段
                Object.keys(this.form).forEach(key => {
                    if (key !== 'headPicture') {
                        formData.append(key, this.form[key])
                    }
                })

                await this.$emit('submit', formData)
                this.$message.success('用户信息更新成功')
            } catch (error) {
                this.$message.error('更新失败')
            } finally {
                this.loading = false
            }
        }
    },
    mounted() {
        const userId = this.$route.params.id
        if (userId) {
            this.getUser(userId)
        } else {
            this.$message.error('无效的用户ID')
            this.$router.back()
        }
    }
}
</script>


<style lang="scss" scoped>
.user-center-container {
    max-width: 800px;
    margin: 40px auto;
    padding: 30px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);

    .user-form {
        padding: 0 50px;

        .custom-input {
            ::v-deep .el-input__inner {
                height: 44px;
                border-radius: 8px;
                padding-left: 40px;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                &:hover {
                    border-color: #409EFF;
                }

                &:focus {
                    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
                }
            }

            .el-icon-user,
            .el-icon-lock,
            .el-icon-mobile-phone {
                color: #909399;
                font-size: 16px;
                margin-left: 8px;
            }
        }

        .avatar-uploader {
            .upload-wrapper {
                width: 120px;
                height: 120px;
                border: 2px dashed #DCDFE6;
                border-radius: 8px;
                position: relative;
                cursor: pointer;
                transition: all 0.3s;
                overflow: hidden;

                &:hover {
                    border-color: #409EFF;
                    background: rgba(64, 158, 255, 0.05);

                    .mask {
                        opacity: 1;
                    }
                }

                .preview-image {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .mask {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    opacity: 0;
                    transition: opacity 0.3s;

                    .el-icon-upload {
                        color: #fff;
                        font-size: 24px;
                    }
                }

                .upload-icon {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    font-size: 28px;
                    color: #8c939d;
                }
            }

            .upload-tip {
                margin-top: 12px;
                font-size: 12px;
                color: #909399;
                line-height: 1.5;
            }
        }

        .status-select {
            width: 100%;

            ::v-deep .el-input__inner {
                border-radius: 8px;
                height: 44px;
            }
        }

        .submit-btn {
            width: 100%;
            height: 48px;
            font-size: 16px;
            letter-spacing: 1px;
            border-radius: 8px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
            }

            .el-icon-upload {
                margin-right: 8px;
            }
        }
    }
}

.hidden-input {
    display: none;
}
</style>